const app = getApp();

Page({
  data: {
    isAuthorized: false,
    userInfo: null,
    userCondition: '',
    globalData: {},
    nfcSupported: false,
    currentNFCDevice: null
  },

  onLoad() {
    this.checkAuthStatus();
    this.updateGlobalData();
  },

  onShow() {
    this.checkAuthStatus();
    this.updateGlobalData();
    this.updateNFCStatus();
  },

  // 检查授权状态
  checkAuthStatus() {
    const isAuthorized = app.globalData.isAuthorized;
    const userInfo = app.globalData.userInfo;
    const userCondition = wx.getStorageSync('userCondition') || '';

    this.setData({
      isAuthorized,
      userInfo,
      userCondition
    });
  },

  // 更新全局数据
  updateGlobalData() {
    this.setData({
      globalData: {
        userInfo: app.globalData.userInfo,
        isAuthorized: app.globalData.isAuthorized,
        env: app.globalData.env,
        nfcSupported: app.globalData.nfcSupported,
        nfcDevice: app.globalData.nfcDevice
      }
    });
  },

  // 更新NFC状态
  updateNFCStatus() {
    this.setData({
      nfcSupported: app.globalData.nfcSupported,
      currentNFCDevice: app.globalData.nfcDevice
    });
  },

  // 测试登录
  testLogin() {
    wx.showLoading({
      title: '测试登录中...'
    });

    app.userLogin().then((userInfo) => {
      wx.hideLoading();
      this.checkAuthStatus();
      this.updateGlobalData();
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
    }).catch((err) => {
      wx.hideLoading();
      wx.showToast({
        title: '登录失败',
        icon: 'error'
      });
      console.error('测试登录失败:', err);
    });
  },

  // 测试退出
  testLogout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          app.logout();
          this.checkAuthStatus();
          this.updateGlobalData();
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
        }
      }
    });
  },

  // 清除数据
  testClearData() {
    wx.showModal({
      title: '确认清除',
      content: '确定要清除所有本地数据吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('userCondition');
          app.globalData.userInfo = null;
          app.globalData.isAuthorized = false;

          this.checkAuthStatus();
          this.updateGlobalData();

          wx.showToast({
            title: '数据已清除',
            icon: 'success'
          });
        }
      }
    });
  },

  // 刷新状态
  testRefresh() {
    this.checkAuthStatus();
    this.updateGlobalData();
    wx.showToast({
      title: '状态已刷新',
      icon: 'success'
    });
  },

  // 页面跳转
  goToHome() {
    wx.switchTab({
      url: '/pages/home/index'
    });
  },

  goToRecord() {
    wx.switchTab({
      url: '/pages/record/index'
    });
  },

  goToVideo() {
    wx.switchTab({
      url: '/pages/video/index'
    });
  },

  goToUser() {
    wx.switchTab({
      url: '/pages/user/index'
    });
  },

  // NFC功能测试
  testNFCStatus() {
    const nfcSupported = app.globalData.nfcSupported;
    wx.showModal({
      title: 'NFC状态',
      content: `NFC支持状态：${nfcSupported ? '支持' : '不支持'}`,
      showCancel: false,
      confirmText: '确定'
    });
  },

  testNFCCompatibility() {
    // 导入NFC工具函数
    const { checkNFCCompatibility } = require('../../utils/nfc.js');
    const compatibility = checkNFCCompatibility();

    const content = `API支持情况：
基础API: ${compatibility.supported ? '✓' : '✗'}
适配器: ${compatibility.adapter ? '✓' : '✗'}
设备发现: ${compatibility.discovered ? '✓' : '✗'}
启动监听: ${compatibility.startDiscovery ? '✓' : '✗'}
停止监听: ${compatibility.stopDiscovery ? '✓' : '✗'}`;

    wx.showModal({
      title: 'NFC兼容性检查',
      content: content,
      showCancel: false,
      confirmText: '确定'
    });
  },

  testNFCStart() {
    if (app.globalData.nfcSupported) {
      try {
        app.startNFCListener();
        wx.showToast({
          title: 'NFC监听已启动',
          icon: 'success'
        });
      } catch (error) {
        console.error('启动NFC监听失败:', error);
        wx.showToast({
          title: '启动NFC监听失败',
          icon: 'error'
        });
      }
    } else {
      wx.showToast({
        title: '设备不支持NFC',
        icon: 'error'
      });
    }
  },

  testNFCStop() {
    app.stopNFCListener();
    wx.showToast({
      title: 'NFC监听已停止',
      icon: 'success'
    });
  },

  testNFCMock() {
    // 模拟NFC设备数据
    const mockDevice = {
      id: '04A123456789',
      type: 'nfc-a',
      name: '模拟NFC卡片',
      manufacturer: 'NXP Semiconductors',
      model: 'Mifare Classic',
      serialNumber: '04A123456789',
      timestamp: new Date().toLocaleString()
    };

    try {
      // 触发NFC设备发现事件
      app.handleNFCDevice(mockDevice);

      wx.showToast({
        title: '模拟设备已触发',
        icon: 'success'
      });
    } catch (error) {
      console.error('模拟NFC设备失败:', error);
      wx.showToast({
        title: '模拟设备失败',
        icon: 'error'
      });
    }
  }
});
